#include<iostream>
#include<cstdio>
#include<sys/mman.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>

#define FILENAME "log.txt"

int main()
{
    //open file
    int fd = open(FILENAME, O_RDONLY);
    if (fd < 0)
    {
        perror("open");
        return 1;
    }

    struct stat st; // struct stat 类型的结构体用于记录文件的属性
    fstat(fd, &st);

    //建立映射
    char* mmap_addr = (char*)mmap(nullptr, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
    if (mmap_addr == MAP_FAILED)
    {
        perror("mmap");
        return 2;
    }

    //读取操作
    std::cout << mmap_addr << std::endl;

    //取消映射
    munmap(mmap_addr, st.st_size);

    //关闭文件
    close(fd);
    std::cout << "读取映射完毕" << std::endl;

    return 0;
}